from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

customer_bp = Blueprint('customer', __name__, url_prefix='/customer')

# 模拟数据库 - 实际项目中应替换为真实数据库操作
accounts_db = [
    {'customer_id': '1001', 'name': '张三', 'cards': [
        {'card_id': '6222021234567890123', 'deposit_type': '活期存款', 'balance': 15000.50, 'open_date': '2023-01-15', 'is_report_loss': False}
    ]},
    {'customer_id': '1002', 'name': '李四', 'cards': [
        {'card_id': '6222029876543210987', 'deposit_type': '定期存款', 'balance': 50000.00, 'open_date': '2023-03-20', 'is_report_loss': False}
    ]}
]

transactions_db = [
    {'id': 1, 'from_card': '6222021234567890123', 'to_card': '6222029876543210987', 'amount': 2000.00, 'date': '2023-06-10', 'status': '成功'},
    {'id': 2, 'from_card': '6222021234567890123', 'to_card': '6222021111111111111', 'amount': 500.00, 'date': '2023-06-15', 'status': '失败'}
]

# 账户信息路由
@customer_bp.route('/account', methods=['GET'])
@jwt_required()
def get_account():
    current_user_id = get_jwt_identity()
    # 查找当前用户
    for account in accounts_db:
        if account['customer_id'] == current_user_id:
            return jsonify(account)
    return jsonify({'success': False, 'message': '账户不存在'}), 404

# 存款路由
@customer_bp.route('/deposit', methods=['POST'])
@jwt_required()
def deposit():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    card_id = data.get('card_id')
    amount = float(data.get('amount', 0))

    if amount <= 0:
        return jsonify({'success': False, 'message': '存款金额必须大于0'}), 400

    # 查找用户和银行卡
    for account in accounts_db:
        if account['customer_id'] == current_user_id:
            for card in account['cards']:
                if card['card_id'] == card_id:
                    # 更新余额
                    card['balance'] += amount
                    # 记录交易
                    new_transaction = {
                        'id': len(transactions_db) + 1,
                        'from_card': '系统',
                        'to_card': card_id,
                        'amount': amount,
                        'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        'status': '成功'
                    }
                    transactions_db.append(new_transaction)
                    return jsonify({
                        'success': True,
                        'message': '存款成功',
                        'new_balance': card['balance'],
                        'transaction': new_transaction
                    })
    return jsonify({'success': False, 'message': '银行卡不存在'}), 404

# 取款路由
@customer_bp.route('/withdraw', methods=['POST'])
@jwt_required()
def withdraw():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    card_id = data.get('card_id')
    amount = float(data.get('amount', 0))
    password = data.get('password')  # 实际项目中应验证密码

    if amount <= 0:
        return jsonify({'success': False, 'message': '取款金额必须大于0'}), 400

    # 查找用户和银行卡
    for account in accounts_db:
        if account['customer_id'] == current_user_id:
            for card in account['cards']:
                if card['card_id'] == card_id:
                    if card['balance'] < amount:
                        return jsonify({'success': False, 'message': '余额不足'}), 400
                    # 更新余额
                    card['balance'] -= amount
                    # 记录交易
                    new_transaction = {
                        'id': len(transactions_db) + 1,
                        'from_card': card_id,
                        'to_card': '系统',
                        'amount': amount,
                        'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        'status': '成功'
                    }
                    transactions_db.append(new_transaction)
                    return jsonify({
                        'success': True,
                        'message': '取款成功',
                        'new_balance': card['balance'],
                        'transaction': new_transaction
                    })
    return jsonify({'success': False, 'message': '银行卡不存在'}), 404

# 转账路由
@customer_bp.route('/transfer', methods=['POST'])
@jwt_required()
def transfer():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    from_card = data.get('from_card')
    to_card = data.get('to_card')
    amount = float(data.get('amount', 0))
    password = data.get('password')  # 实际项目中应验证密码

    if amount <= 0:
        return jsonify({'success': False, 'message': '转账金额必须大于0'}), 400

    if from_card == to_card:
        return jsonify({'success': False, 'message': '不能向自己转账'}), 400

    # 查找转出卡
    from_account = None
    from_card_obj = None
    for account in accounts_db:
        for card in account['cards']:
            if card['card_id'] == from_card:
                from_account = account
                from_card_obj = card
                break
        if from_account:
            break

    if not from_card_obj:
        return jsonify({'success': False, 'message': '转出卡不存在'}), 404

    if from_account['customer_id'] != current_user_id:
        return jsonify({'success': False, 'message': '无权操作此银行卡'}), 403

    if from_card_obj['balance'] < amount:
        return jsonify({'success': False, 'message': '余额不足'}), 400

    # 查找转入卡
    to_card_obj = None
    for account in accounts_db:
        for card in account['cards']:
            if card['card_id'] == to_card:
                to_card_obj = card
                break
        if to_card_obj:
            break

    if not to_card_obj:
        return jsonify({'success': False, 'message': '转入卡不存在'}), 404

    # 更新余额
    from_card_obj['balance'] -= amount
    to_card_obj['balance'] += amount

    # 记录交易
    new_transaction = {
        'id': len(transactions_db) + 1,
        'from_card': from_card,
        'to_card': to_card,
        'amount': amount,
        'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'status': '成功'
    }
    transactions_db.append(new_transaction)

    return jsonify({
        'success': True,
        'message': '转账成功',
        'new_balance': from_card_obj['balance'],
        'transaction': new_transaction
    })

# 交易记录路由
@customer_bp.route('/transactions', methods=['GET'])
@jwt_required()
def get_transactions():
    current_user_id = get_jwt_identity()
    card_id = request.args.get('card_id')

    # 获取用户所有卡号
    user_cards = []
    for account in accounts_db:
        if account['customer_id'] == current_user_id:
            user_cards = [card['card_id'] for card in account['cards']]
            break

    # 筛选交易记录
    filtered = []
    for t in transactions_db:
        if (t['from_card'] in user_cards or t['to_card'] in user_cards) and \
           (not card_id or t['from_card'] == card_id or t['to_card'] == card_id):
            filtered.append(t)

    return jsonify({'transactions': filtered})

# 修改密码路由
@customer_bp.route('/change-password', methods=['POST'])
@jwt_required()
def change_password():
    current_user_id = get_jwt_identity()
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')

    # 实际项目中应从数据库获取并验证旧密码
    # 这里简化处理，假设旧密码正确
    if not old_password or not new_password:
        return jsonify({'success': False, 'message': '密码不能为空'}), 400

    if len(new_password) < 6:
        return jsonify({'success': False, 'message': '新密码长度不能少于6位'}), 400

    # 实际项目中应更新数据库中的密码
    return jsonify({'success': True, 'message': '密码修改成功'})